
/**
 * @ProjectName: 
 * @Copyright: 2014 lisheng  All Right Reserved.
 * @address: toughheart@163.com
 * @date: 2016年1月12日 下午9:29:29
 * @Description: 本内容未经本人允许禁止使用、转发.
 */
 
package com.ls.fw.auth.oauth2.as.handler.impl;

import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuer;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.as.request.OAuthAuthzRequest;
import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.apache.oltu.oauth2.common.message.types.ResponseType;

import com.ls.fw.auth.oauth2.as.def.Constant;
import com.ls.fw.auth.oauth2.as.exception.OAuth2Exception;
import com.ls.fw.auth.oauth2.as.handler.OAuth2Handler;
import com.ls.fw.auth.oauth2.as.service.OAuthService;


/**
 * 
 * @author lisheng
 * @date 2016年1月12日 下午9:29:29
 * @version V1.0 
 */
public class OAuth2HandlerImpl implements OAuth2Handler{
	 
	private OAuthService oauthService;

	private OAuthIssuer oauthIssuer = new OAuthIssuerImpl(new MD5Generator());
	
	public OAuth2HandlerImpl() {
		super();
	}

	public OAuth2HandlerImpl(OAuthService oauthService) {
		super();
		this.oauthService = oauthService;
	}

	public OAuth2HandlerImpl(OAuthService oauthService, OAuthIssuer oauthIssuer) {
		super();
		this.oauthService = oauthService;
		this.oauthIssuer = oauthIssuer;
	}

	 
	
	
	@Override
	public String getAccessTokenByRefreshToken(OAuthTokenRequest oauthRequest) throws OAuth2Exception, OAuthSystemException{
        String token = null;
        //检查提交的客户端id是否正确
        if (!oauthService.checkClientId(oauthRequest.getClientId())) {
         	throw new OAuth2Exception(OAuthError.TokenResponse.INVALID_CLIENT,"无效的客户端ID:"+OAuth.OAUTH_CLIENT_ID+"！");
        }
        String refresh_token = oauthRequest.getParam(OAuth.OAUTH_REFRESH_TOKEN);
        
        // 检查验证类型，此处只检查AUTHORIZATION_CODE类型，其他的还有PASSWORD或REFRESH_TOKEN
        if (GrantType.REFRESH_TOKEN.toString().equals(oauthRequest.getParam(OAuth.OAUTH_REFRESH_TOKEN))) {
            if (oauthService.checkRefreshToken(refresh_token)) {
               //生成Access Token
                token = oauthService.getAccessTokenByRefreshToken(refresh_token);
                if(!oauthService.checkAccessToken(token)){//过期
                    token = oauthIssuer.accessToken();
                    oauthService.addRefreshToken(refresh_token, token);
                } 
                oauthService.addAccessToken(token, oauthRequest.getClientId());
            }else{
            	throw new OAuth2Exception(Constant.ERROR_42002+"","refresh_token超时");
            }
        }else{
          	throw new OAuth2Exception(Constant.ERROR_40030+"",OAuth.OAUTH_REFRESH_TOKEN+"无效");
        }
        return token;
	}
	

	@Override
	public String getRefreshTokenByRefreshToken(OAuthTokenRequest oauthRequest) throws OAuth2Exception, OAuthSystemException{
		String accessToken = null;

        String refreshToken = oauthRequest.getParam(OAuth.OAUTH_REFRESH_TOKEN);
        // 检查验证类型，此处只检查AUTHORIZATION_CODE类型，其他的还有PASSWORD或REFRESH_TOKEN
        if (GrantType.REFRESH_TOKEN.toString().equals(oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE))) {
            if (!oauthService.checkRefreshToken(refreshToken)) {
                throw new OAuth2Exception(OAuthError.TokenResponse.INVALID_GRANT,"错误的授权码"+OAuth.OAUTH_REFRESH_TOKEN+"！");
            }
        }else{
            throw new OAuth2Exception(OAuthError.TokenResponse.INVALID_GRANT,"错误的"+OAuth.OAUTH_GRANT_TYPE+"！");
        }
        accessToken = oauthIssuer.refreshToken();
        oauthService.addAccessToken(accessToken, oauthRequest.getClientId());
		return accessToken;
	}
	
	@Override
	public String getRefreshToken(OAuthTokenRequest oauthRequest) throws OAuth2Exception, OAuthSystemException{
		String accessToken = null;
        //检查提交的客户端id是否正确
        if (!oauthService.checkClientId(oauthRequest.getClientId())) {
        	throw new OAuth2Exception(OAuthError.TokenResponse.INVALID_CLIENT,"无效的客户端ID:"+OAuth.OAUTH_CLIENT_ID+"！");
        }
        //生成Access Token
        accessToken = oauthIssuer.refreshToken();
        oauthService.addAccessToken(accessToken, oauthRequest.getClientId());
		return accessToken;
	}
	@Override
	public String getRefreshTokenByCode(OAuthTokenRequest oauthRequest) throws OAuth2Exception, OAuthSystemException{
		String accessToken = null;
        //检查提交的客户端id是否正确
        if (!oauthService.checkClientId(oauthRequest.getClientId())) {
        	throw new OAuth2Exception(OAuthError.TokenResponse.INVALID_CLIENT,"无效的客户端ID:"+OAuth.OAUTH_CLIENT_ID+"！");
        }

        // 检查客户端安全KEY是否正确
        if (!oauthService.checkClientSecret(oauthRequest.getClientId(),oauthRequest.getClientSecret())) {
            throw new OAuth2Exception(OAuthError.TokenResponse.INVALID_CLIENT,"无效的客户端安全KEY:"+OAuth.OAUTH_CLIENT_SECRET+"！");
        }
       
        String authCode = oauthRequest.getParam(OAuth.OAUTH_CODE);
        if (GrantType.AUTHORIZATION_CODE.toString().equals(oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE))) {
            if (!oauthService.checkAuthCode(authCode)) {
                throw new OAuth2Exception(OAuthError.TokenResponse.INVALID_GRANT,"错误的授权码"+OAuth.OAUTH_CODE+"！");
            }
        }else{
            throw new OAuth2Exception(OAuthError.TokenResponse.INVALID_GRANT,"错误的"+OAuth.OAUTH_GRANT_TYPE+"！");
        }
        //生成Access Token
        accessToken = oauthIssuer.refreshToken();
        oauthService.addAccessToken(accessToken, oauthService.getUsernameByAuthCode(authCode));
		return accessToken;
	}
	
	@Override
	public String getAccessTokenByCode(OAuthTokenRequest oauthRequest) throws OAuth2Exception, OAuthSystemException{
		String accessToken = null;
        //检查提交的客户端id是否正确
        if (!oauthService.checkClientId(oauthRequest.getClientId())) {
        	throw new OAuth2Exception(OAuthError.TokenResponse.INVALID_CLIENT,"无效的客户端ID:"+OAuth.OAUTH_CLIENT_ID+"！");
        }

        // 检查客户端安全KEY是否正确
        if (!oauthService.checkClientSecret(oauthRequest.getClientId(),oauthRequest.getClientSecret())) {
            throw new OAuth2Exception(OAuthError.TokenResponse.INVALID_CLIENT,"无效的客户端安全KEY:"+OAuth.OAUTH_CLIENT_SECRET+"！");
        }

        String authCode = oauthRequest.getParam(OAuth.OAUTH_CODE);
        // 检查验证类型，此处只检查AUTHORIZATION_CODE类型，其他的还有PASSWORD或REFRESH_TOKEN
        if (GrantType.AUTHORIZATION_CODE.toString().equals(oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE))) {
            if (!oauthService.checkAuthCode(authCode)) {
                throw new OAuth2Exception(OAuthError.TokenResponse.INVALID_GRANT,"错误的授权码"+OAuth.OAUTH_CODE+"！");
            }
        }else{
            throw new OAuth2Exception(OAuthError.TokenResponse.INVALID_GRANT,"错误的"+OAuth.OAUTH_GRANT_TYPE+"！");
        }
        //生成Access Token
        accessToken = oauthIssuer.accessToken();
        oauthService.addAccessToken(accessToken, oauthService.getUsernameByAuthCode(authCode));
		return accessToken;
	}
	
	@Override
	public String getAuthCode(OAuthAuthzRequest oauthRequest) throws OAuth2Exception, OAuthSystemException{
        //检查传入的客户端id是否正确
        if (!oauthService.checkClientId(oauthRequest.getClientId())) {
            throw new OAuth2Exception(OAuthError.TokenResponse.INVALID_CLIENT,"无效的客户端ID:"+OAuth.OAUTH_CLIENT_ID+"！");
        }
        //如果用户没有登录，跳转到登陆页面
        String clientId = oauthRequest.getClientId(); //获取用户名
        //生成授权码
        String authorizationCode = null;
        String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
        if (OAuth.OAUTH_CODE.toString().equals(responseType)) {
            authorizationCode = oauthIssuer.authorizationCode();
            oauthService.addAuthCode(authorizationCode, clientId);
        }else{
            throw new OAuth2Exception(OAuthError.TokenResponse.INVALID_CLIENT,"参数"+OAuth.OAUTH_RESPONSE_TYPE+"无效！");
        }
        return authorizationCode;
	}
	
	
	@Override
	public String getAccessToken(OAuthAuthzRequest oauthRequest) throws OAuthSystemException{
		 //build response according to response_type
        String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
        String token = null;
        if (responseType.equals(ResponseType.TOKEN.toString())) {
        	token = oauthIssuer.accessToken();
        }
        return token;
	}
	
	@Override
	public OAuthService getOauthService() {
		return oauthService;
	}

	public void setOauthService(OAuthService oauthService) {
		this.oauthService = oauthService;
	}

	@Override
	public OAuthIssuer getOauthIssuer() {
		return oauthIssuer;
	}

	public void setOauthIssuer(OAuthIssuer oauthIssuer) {
		this.oauthIssuer = oauthIssuer;
	}

}
